using System.Xml.Linq;

namespace Chaotic.DataBase.DBAccessLibrary.Common;

public class ChDescriptionXml
{
	protected readonly string _path;

	private readonly Dictionary<string, string> _cache = new Dictionary<string, string>();

	public string ChDescription
	{
		get => GetElement("ChDescription");
        set
		{
			XElement xElement = XElement.Load(_path);
			XElement? xElement2 = xElement.Elements().FirstOrDefault(o => o.Name.LocalName == "ChDescription");
			if (xElement2 == null)
			{
				xElement2 = new XElement("ChDescription");
				XComment content = new XComment("以下填写获取中文信息的SQL语句，列名必须有TABLENAME,CHINATABLENAME,COLUMNNAME,CHINACOLUMNNAME 这4个字段");
				xElement2.Add(content);
				xElement.Add(xElement2);
			}
			xElement2.Value = value;
			xElement.Save(_path);
		}
	}

	public ChDescriptionXml()
	{
		_path = AppDomain.CurrentDomain.BaseDirectory + "\\QueryConfig.xml";
		VerityXml();
	}

	private void VerityXml()
	{
		if (!File.Exists(_path))
		{
			XElement xElement = new XElement("Query");
			XDocument xDocument = new XDocument(new XDeclaration("1.0", "utf-8", "yes"), xElement);
			xDocument.Save(_path);
		}
	}

	protected string GetElement(string elementName)
	{
		if (_cache.TryGetValue(elementName, out var element))
		{
			return element;
		}
		XElement xElement = XElement.Load(_path);
		XElement? xElement2 = xElement.Elements().FirstOrDefault(o => o.Name.LocalName == elementName);
		if (xElement2 == null)
		{
			return string.Empty;
		}
		return xElement2.Value;
	}

	protected void SetElement(string elementName, string elementValue)
	{
		if (!string.IsNullOrEmpty(elementValue) && (!_cache.ContainsKey(elementName) || _cache[elementName] != elementValue))
		{
			XElement xElement = XElement.Load(_path);
			XElement? xElement2 = xElement.Elements().FirstOrDefault(o => o.Name.LocalName == elementName);
			if (xElement2 == null)
			{
				xElement2 = new XElement(elementName);
				xElement.Add(xElement2);
			}
			xElement2.Value = elementValue;
			xElement.Save(_path);
			if (_cache.ContainsKey(elementName))
			{
				_cache[elementName] = elementValue;
			}
		}
	}
}
